package com.info33.platform.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info33.platform.common.constant.TableConstant;
import com.info33.platform.common.exception.TransactionalException;
import com.info33.platform.common.mvc.vo.Result;
import com.info33.platform.system.dao.SysAppMenuRoleDao;
import com.info33.platform.system.dto.SysAppMenuRoleDTO;
import com.info33.platform.system.dto.SysPostDTO;
import com.info33.platform.system.dto.SysUserDTO;
import com.info33.platform.system.entity.SysAppMenuRole;
import com.info33.platform.system.entity.SysPost;
import com.info33.platform.system.service.SysAppMenuRoleService;
import com.info33.platform.system.vo.SysAppMenuVO;
import com.info33.platform.system.vo.SysPostVO;
import com.info33.platform.system.vo.SysTenantUserVO;
import com.info33.platform.system.vo.SysUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author admin
 */
@Service
public class SysAppMenuRoleServiceImpl extends ServiceImpl<SysAppMenuRoleDao, SysAppMenuRole> implements SysAppMenuRoleService {

    @Autowired
    private SysAppMenuRoleDao sysAppMenuRoleDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result<Object> pcBindRole(SysAppMenuRoleDTO dto) {
        List<Object> oldList = sysAppMenuRoleDao.selectObjs(new QueryWrapper<SysAppMenuRole>()
                .select("menu_id")
                .eq("type", 3)
                .eq("role_id", dto.getRoleId())
                .eq(TableConstant.TENANT_ID, dto.getTenantId()));
        ArrayList<SysAppMenuRole> saveList = new ArrayList<>();
        dto.getMenuIds().forEach(l -> {
            SysAppMenuRole entity = new SysAppMenuRole();
            entity.setMenuId(l);
            entity.setRoleId(dto.getRoleId());
            entity.setType(1);
            // 过滤掉已存在的旧数据
            if (!oldList.contains(l)) {
                saveList.add(entity);
            }
        });
        if (!ObjectUtils.isEmpty(saveList) && Boolean.FALSE.equals(this.saveBatch(saveList))) {
            throw new TransactionalException();
        }
        return Result.ok();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result<Object> pcBindUser(SysAppMenuRoleDTO dto) {
        List<SysAppMenuRole> oldList = sysAppMenuRoleDao.selectList(new QueryWrapper<SysAppMenuRole>()
                .select("menu_id", "user_id", "type")
                .eq("type", 2)
                .eq(TableConstant.TENANT_ID, dto.getTenantId())
                .apply("FIND_IN_SET(user_id, {0}) > 0", dto.getUserIds()));
        ArrayList<SysAppMenuRole> saveList = new ArrayList<>();
        for (String s : dto.getUserIds().split(TableConstant.COMMA)) {
            dto.getMenuIds().forEach(l -> {
                SysAppMenuRole entity = new SysAppMenuRole();
                entity.setMenuId(l);
                entity.setUserId(Long.parseLong(s));
                entity.setType(2);
                // 过滤掉已存在的旧数据
                if (!oldList.contains(entity)) {
                    saveList.add(entity);
                }
            });
        }
        if (!ObjectUtils.isEmpty(saveList) && Boolean.FALSE.equals(this.saveBatch(saveList))) {
            throw new TransactionalException();
        }
        return Result.ok();
    }

    @Override
    public Result<Object> pcBindAll(SysAppMenuRoleDTO dto) {
        List<Object> oldList = sysAppMenuRoleDao.selectObjs(new QueryWrapper<SysAppMenuRole>()
                .select("menu_id")
                .eq("type", 3)
                .eq(TableConstant.TENANT_ID, dto.getTenantId()));
        ArrayList<SysAppMenuRole> saveList = new ArrayList<>();
        dto.getMenuIds().forEach(l -> {
            SysAppMenuRole entity = new SysAppMenuRole();
            entity.setMenuId(l);
            entity.setType(3);
            // 过滤掉已存在的旧数据
            if (!oldList.contains(l)) {
                saveList.add(entity);
            }
        });
        if (!ObjectUtils.isEmpty(saveList) && Boolean.FALSE.equals(this.saveBatch(saveList))) {
            throw new TransactionalException();
        }
        return Result.ok();
    }

    @Override
    public IPage<SysUserVO> pcUser(Page<SysUserVO> page, SysUserDTO dto) {
        return sysAppMenuRoleDao.pcUser(page, dto);
    }

    @Override
    public IPage<SysPostVO> pcRole(Page<SysPost> page, SysPostDTO dto) {
        return sysAppMenuRoleDao.pcRole(page, dto);
    }

    @Override
    public SysTenantUserVO pcUserDetail(Long uid) {
        return sysAppMenuRoleDao.pcUserDetail(uid);
    }

    @Override
    public SysPostVO pcRoleDetail(Long rid) {
        return sysAppMenuRoleDao.pcRoleDetail(rid);
    }

    @Override
    public Result<Object> pcEditUser(SysAppMenuRoleDTO dto) {
        List<SysAppMenuRole> oldList = sysAppMenuRoleDao.selectList(new QueryWrapper<SysAppMenuRole>()
                .select(TableConstant.ID)
                .eq("user_id", dto.getUserId())
                .eq("type", 2));
        if (!ObjectUtils.isEmpty(oldList) && sysAppMenuRoleDao.deleteBatchIds(oldList.stream().map(SysAppMenuRole::getId).collect(Collectors.toList())) != oldList.size()) {
            // 去除旧配置
            return Result.error(Result.RESULT_ERROR_PUBLIC_MSG);
        }
        ArrayList<SysAppMenuRole> saveList = new ArrayList<>();
        dto.getMenuIds().forEach(l -> {
            SysAppMenuRole entity = new SysAppMenuRole();
            entity.setMenuId(l);
            entity.setUserId(dto.getUserId());
            entity.setType(2);
            saveList.add(entity);
        });
        if (!ObjectUtils.isEmpty(saveList) && Boolean.FALSE.equals(this.saveBatch(saveList))) {
            throw new TransactionalException();
        }
        return Result.ok();
    }

    @Override
    public Result<Object> pcEditRole(SysAppMenuRoleDTO dto) {
        List<SysAppMenuRole> oldList = sysAppMenuRoleDao.selectList(new QueryWrapper<SysAppMenuRole>()
                .select(TableConstant.ID)
                .eq("role_id", dto.getRoleId())
                .eq("type", 1));
        if (!ObjectUtils.isEmpty(oldList) && sysAppMenuRoleDao.deleteBatchIds(oldList.stream().map(SysAppMenuRole::getId).collect(Collectors.toList())) != oldList.size()) {
            // 去除旧配置
            return Result.error(Result.RESULT_ERROR_PUBLIC_MSG);
        }
        ArrayList<SysAppMenuRole> saveList = new ArrayList<>();
        dto.getMenuIds().forEach(l -> {
            SysAppMenuRole entity = new SysAppMenuRole();
            entity.setMenuId(l);
            entity.setRoleId(dto.getRoleId());
            entity.setType(1);
            saveList.add(entity);
        });
        if (!ObjectUtils.isEmpty(saveList) && Boolean.FALSE.equals(this.saveBatch(saveList))) {
            throw new TransactionalException();
        }
        return Result.ok();
    }

    @Override
    public List<SysAppMenuVO> pcAll(Long tenantId) {
        return sysAppMenuRoleDao.pcAll(tenantId);
    }

    @Override
    public Result<Object> pcEditAll(SysAppMenuRoleDTO dto) {
        List<SysAppMenuRole> oldList = sysAppMenuRoleDao.selectList(new QueryWrapper<SysAppMenuRole>()
                .select(TableConstant.ID)
                .eq("type", 3)
                .eq(TableConstant.TENANT_ID, dto.getTenantId()));
        if (!ObjectUtils.isEmpty(oldList) && sysAppMenuRoleDao.deleteBatchIds(oldList.stream().map(SysAppMenuRole::getId).collect(Collectors.toList())) != oldList.size()) {
            // 去除旧配置
            return Result.error(Result.RESULT_ERROR_PUBLIC_MSG);
        }
        ArrayList<SysAppMenuRole> saveList = new ArrayList<>();
        dto.getMenuIds().forEach(l -> {
            SysAppMenuRole entity = new SysAppMenuRole();
            entity.setMenuId(l);
            entity.setType(3);
            saveList.add(entity);
        });
        if (Boolean.FALSE.equals(this.saveBatch(saveList))) {
            throw new TransactionalException();
        }
        return Result.ok();
    }

}